<template>
  <div class="profile">
    <div class="header">
      <h2>个人中心</h2>
    </div>

    <div class="content-container">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-card class="user-card">
            <div class="user-info">
              <div class="avatar-container">
                <el-avatar :size="100" :src="userInfo.avatar" :alt="userInfo.name">
                  <img src="/public/default avatar.png" alt="默认头像" />
                </el-avatar>
                <el-button type="primary" size="small" class="avatar-btn" @click="handleUploadAvatar">
                  更换头像
                </el-button>
                <input type="file" ref="avatarInput" style="display: none" accept="image/*"
                  @change="handleAvatarChange" />
              </div>
              <h3>{{ userInfo.name }}</h3>
              <p class="user-role">{{ userInfo.roleName }}</p>
              <p class="user-id">ID: {{ userInfo.id }}</p>
            </div>
            <div class="user-stats">
              <el-row :gutter="10">
                <el-col :span="8">
                  <div class="stat-item">
                    <div class="stat-value">{{ statistics.loginCount || 0 }}</div>
                    <div class="stat-label">登录次数</div>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="stat-item">
                    <div class="stat-value">{{ statistics.operationCount || 0 }}</div>
                    <div class="stat-label">操作次数</div>
                  </div>
                </el-col>
                <el-col :span="8">
                  <div class="stat-item">
                    <div class="stat-value">{{ statistics.notificationCount || 0 }}</div>
                    <div class="stat-label">未读通知</div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-card>
        </el-col>

        <el-col :span="16">
          <el-tabs v-model="activeTab" type="card">
            <el-tab-pane label="基本信息" name="info">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>基本信息</span>
                    <el-button type="primary" @click="handleEditProfile">编辑</el-button>
                  </div>
                </template>
                <el-descriptions :column="2" border>
                  <el-descriptions-item label="用户名">{{ userInfo.username }}</el-descriptions-item>
                  <el-descriptions-item label="姓名">{{ userInfo.name }}</el-descriptions-item>
                  <el-descriptions-item label="性别">{{ userInfo.gender === 1 ? '男' : '女' }}</el-descriptions-item>
                  <el-descriptions-item label="邮箱">{{ userInfo.email }}</el-descriptions-item>
                  <el-descriptions-item label="手机号">{{ userInfo.phone }}</el-descriptions-item>
                  <el-descriptions-item label="角色">{{ userInfo.roleName }}</el-descriptions-item>
                  <el-descriptions-item label="创建时间">{{ formatDate(userInfo.created) }}</el-descriptions-item>
                  <!-- <el-descriptions-item label="最后登录">{{ formatDate(userInfo.lastLoginTime) }}</el-descriptions-item> -->
                </el-descriptions>
              </el-card>
            </el-tab-pane>

            <el-tab-pane label="安全设置" name="security">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>安全设置</span>
                  </div>
                </template>
                <div class="security-section">
                  <div class="security-item">
                    <div class="security-info">
                      <h4>登录密码</h4>
                      <p>定期更换密码，保护账户安全</p>
                    </div>
                    <el-button type="primary" @click="handleChangePassword">修改密码</el-button>
                  </div>
                </div>
              </el-card>
            </el-tab-pane>

            <el-tab-pane label="操作日志" name="logs">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>操作日志</span>
                    <el-button type="primary" @click="handleRefreshLogs">刷新</el-button>
                  </div>
                </template>
                <el-table :data="logs" style="width: 100%" max-height="400">
                  <el-table-column prop="operation" label="操作" width="150" />
                  <el-table-column prop="description" label="描述" />
                  <el-table-column prop="ip" label="IP地址" width="130" />
                  <el-table-column prop="createTime" label="时间" width="180">
                    <template #default="scope">
                      {{ formatDate(scope.row.createTime) }}
                    </template>
                  </el-table-column>
                </el-table>
                <div class="pagination-container">
                  <el-pagination v-model:current-page="logsParams.page" v-model:page-size="logsParams.size"
                    :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="logsTotal"
                    @size-change="handleLogsSizeChange" @current-change="handleLogsCurrentChange" />
                </div>
              </el-card>
            </el-tab-pane>

            <el-tab-pane label="通知消息" name="notifications">
              <el-card>
                <template #header>
                  <div class="card-header">
                    <span>通知消息</span>
                    <el-button type="primary" @click="handleRefreshNotifications">刷新</el-button>
                  </div>
                </template>
                <el-table :data="notifications" style="width: 100%" max-height="400">
                  <el-table-column prop="title" label="标题" width="200" />
                  <el-table-column prop="content" label="内容" />
                  <el-table-column prop="createTime" label="时间" width="180">
                    <template #default="scope">
                      {{ formatDate(scope.row.createTime) }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="isRead" label="状态" width="80">
                    <template #default="scope">
                      <el-tag :type="scope.row.isRead ? 'info' : 'danger'">
                        {{ scope.row.isRead ? '已读' : '未读' }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="150">
                    <template #default="scope">
                      <el-button v-if="!scope.row.isRead" size="small" type="primary"
                        @click="handleMarkRead(scope.row)">
                        标记已读
                      </el-button>
                      <el-button size="small" type="danger" @click="handleDeleteNotification(scope.row)">
                        删除
                      </el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <div class="pagination-container">
                  <el-pagination v-model:current-page="notificationsParams.page"
                    v-model:page-size="notificationsParams.size" :page-sizes="[10, 20, 50, 100]"
                    layout="total, sizes, prev, pager, next, jumper" :total="notificationsTotal"
                    @size-change="handleNotificationsSizeChange" @current-change="handleNotificationsCurrentChange" />
                </div>
              </el-card>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </div>

    <!-- 修改密码对话框 -->
    <el-dialog v-model="passwordDialogVisible" title="修改密码" width="400px">
      <el-form :model="passwordForm" :rules="passwordRules" ref="passwordFormRef" label-width="80px">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordForm.oldPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="passwordDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmitPassword">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getUserInfo,
  updateUserInfo,
  changePassword,
  uploadAvatar,
  getUserLogs,
  getUserNotifications,
  markNotificationRead,
  deleteNotification,
  getUserStatistics
} from '@/api/profile'

const router = useRouter()

// 当前激活的标签页
const activeTab = ref('info')

// 用户信息
const userInfo = ref({})

// 用户统计数据
const statistics = ref({})

// 操作日志
const logs = ref([])
const logsTotal = ref(0)
const logsParams = reactive({
  page: 1,
  size: 10,
  userId: localStorage.getItem('userId')
})

// 通知消息
const notifications = ref([])
const notificationsTotal = ref(0)
const notificationsParams = reactive({
  page: 1,
  size: 10
})

// 修改密码对话框
const passwordDialogVisible = ref(false)
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const userForm = reactive({
  id: '',
  username: '',
  name: '',
  gender: 1,
  email: '',
  phone: '',
  roleName: '',
  avatar: '',
  bio: '',
  createTime: ''
})



const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入原密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const passwordFormRef = ref(null)
const avatarInput = ref(null)
const userFormRef = ref(null)

// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const res = await getUserInfo(localStorage.getItem('token'))
    if (res.code === 200) {
      userInfo.value = res.data
    } else {
      console.error('获取用户信息失败:', res.message)
      ElMessage.error('获取用户信息失败')
      userInfo.value = {}
    }
  } catch (error) {
    console.error('获取用户信息失败:', error)
    ElMessage.error('获取用户信息失败')
    userInfo.value = {}
  }
}

// 获取用户统计数据
const fetchUserStatistics = async () => {
  try {
    const res = await getUserStatistics()
    if (res.code === 200) {
      statistics.value = res.data
    } else {
      console.error('获取用户统计数据失败:', res.message)
    }
  } catch (error) {
    console.error('获取用户统计数据失败:', error)
  }
}

// 获取操作日志
const fetchUserLogs = async () => {
  try {
    const res = await getUserLogs(logsParams)
    if (res.code === 200) {
      logs.value = res.data.records || []
      logsTotal.value = res.data.total || 0
    } else {
      console.error('获取操作日志失败:', res.message)
    }
  } catch (error) {
    console.error('获取操作日志失败:', error)
  }
}

// 获取通知消息
const fetchUserNotifications = async () => {
  try {
    const res = await getUserNotifications(notificationsParams)
    if (res.code === 200) {
      notifications.value = res.data.records || []
      notificationsTotal.value = res.data.total || 0
    } else {
      console.error('获取通知消息失败:', res.message)
    }
  } catch (error) {
    console.error('获取通知消息失败:', error)
  }
}

// 编辑个人信息
const handleEditProfile = () => {
  router.push('/profile-edit')
}

// 修改密码
const handleChangePassword = () => {
  passwordDialogVisible.value = true
  // 重置表单
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
}

// 提交修改密码
const handleSubmitPassword = async () => {
  try {
    await passwordFormRef.value.validate()

    try {
      const res = await changePassword({
        oldPassword: passwordForm.oldPassword,
        newPassword: passwordForm.newPassword
      })
      if (res.code === 200) {
        ElMessage.success('密码修改成功')
        passwordDialogVisible.value = false
      } else {
        console.log('修改密码失败:', res.message)
        ElMessage.error('密码修改失败: ' + res.message)
      }
    } catch (error) {
      ElMessage.error('密码修改失败: ' + error.response.data['message'])
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 上传头像
const handleUploadAvatar = () => {
  console.log('点击上传头像按钮')
  avatarInput.value.click()
}

// 头像文件变化
const handleAvatarChange = async (event) => {
  console.log('文件选择变化事件触发')
  const file = event.target.files[0]
  if (!file) {
    console.log('未选择文件')
    return
  }

  console.log('选择的文件:', {
    name: file.name,
    type: file.type,
    size: file.size,
    lastModified: new Date(file.lastModified).toLocaleString()
  })

  // 检查文件类型
  if (!file.type.startsWith('image/')) {
    console.log('文件类型不符合要求:', file.type)
    ElMessage.error('请选择图片文件')
    return
  }

  // 检查文件大小（限制为2MB）
  if (file.size > 2 * 1024 * 1024) {
    console.log('文件大小超过限制:', file.size)
    ElMessage.error('图片大小不能超过2MB')
    return
  }

  try {
    const formData = new FormData()
    formData.append('file', file)
    
    console.log('FormData 创建完成，准备上传')
    for (let [key, value] of formData.entries()) {
      console.log('FormData字段:', key, value)
    }

    console.log('开始调用 uploadAvatar API...')
    const res = await uploadAvatar(formData)
    
    console.log('API调用完成，响应:', res)

if (res && res.code === 200) {
  console.log('上传成功，返回数据详情:', JSON.stringify(res.data, null, 2))
  
  let avatarUrl = ''
  
  if (res.data.avatarUrl) {
    avatarUrl = res.data.avatarUrl
    console.log('从响应中获取avatarUrl:', avatarUrl)
  } else {
    console.log('响应中没有avatarUrl字段，尝试其他字段:', Object.keys(res.data))
    if (res.data.url) avatarUrl = res.data.url
    else if (res.data.fileName) avatarUrl = res.data.fileName
    else if (typeof res.data === 'string') avatarUrl = res.data
  }
  
  console.log('最终确定的avatarUrl:', avatarUrl)
  
  // 构建完整URL
  if (avatarUrl) {
    let finalUrl = avatarUrl
    
    if (avatarUrl.startsWith('/static/')) {
      finalUrl = `http://localhost:8085${avatarUrl}`
      console.log('路径以/static/开头，构建URL:', finalUrl)
    } else if (avatarUrl.startsWith('http')) {
      console.log('已经是完整URL:', finalUrl)
    } else {
      finalUrl = `http://localhost:8085/static/${avatarUrl}`
      console.log('普通文件名，构建URL:', finalUrl)
    }
    
    // 使用 nextTick 确保DOM更新
    await nextTick()
    userForm.avatar = finalUrl
    console.log('已更新userForm.avatar:', userForm.avatar)
    
    // 再次强制更新
    await nextTick()
  } else {
    console.warn('没有获取到有效的avatarUrl')
    throw new Error('服务器未返回头像URL')
  }
  
  ElMessage.success('头像上传成功')
  
  // 测试图片是否能访问
  testImageLoad(userForm.avatar)
} else {
      const errorMsg = res?.msg || res?.message || '上传失败'
      console.error('上传失败，响应码:', res?.code, '错误信息:', errorMsg)
      ElMessage.error(`头像上传失败: ${errorMsg}`)
      
      // 上传失败时使用本地预览 - 传递 userForm
      useLocalPreview(file, userForm)
    }
  } catch (error) {
    console.error('头像上传捕获到错误:', error)
    
    // 详细错误处理
    if (error.name === 'AbortError') {
      ElMessage.error('头像上传超时，请检查网络连接')
    } else if (error.response) {
      console.error('服务器错误响应详情:', {
        status: error.response.status,
        statusText: error.response.statusText,
        data: error.response.data
      })
      ElMessage.error(`服务器错误: ${error.response.status} - ${error.response.data?.msg || error.response.statusText}`)
    } else if (error.request) {
      console.error('网络错误，请求对象:', error.request)
      ElMessage.error('网络错误，请检查服务器是否正常运行')
    } else {
      console.error('其他错误详情:', error.message)
      ElMessage.error(`上传失败: ${error.message}`)
    }
    
    // 上传失败时使用本地预览 - 传递 userForm
    useLocalPreview(file, userForm)
  } finally {
    // 清空文件输入
    event.target.value = ''
    console.log('文件输入已清空')
  }
}

// 提取本地预览功能为独立函数 - 接收 form 参数
const useLocalPreview = (file, form) => {
  console.log('开始使用本地预览')
  const reader = new FileReader()
  reader.onload = (e) => {
    form.avatar = e.target.result
    console.log('本地预览设置成功，数据URL长度:', e.target.result.length)
    ElMessage.success('头像已更新（本地预览）')
  }
  reader.onerror = (e) => {
    console.error('FileReader错误详情:', e)
    ElMessage.error('文件读取失败')
  }
  reader.onprogress = (e) => {
    if (e.lengthComputable) {
      console.log(`文件读取进度: ${(e.loaded / e.total * 100).toFixed(2)}%`)
    }
  }
  reader.readAsDataURL(file)
}

// 测试图片是否能加载
const testImageLoad = (url) => {
  console.log('开始测试图片加载:', url)
  const img = new Image()
  
  // 设置超时
  const timeout = setTimeout(() => {
    console.log('图片加载超时:', url)
    img.onload = img.onerror = null // 清除事件监听
  }, 10000)
  
  img.onload = () => {
    clearTimeout(timeout)
    console.log('✅ 图片加载成功:', url)
    ElMessage.success('头像更新完成')
  }
  
  img.onerror = (e) => {
    clearTimeout(timeout)
    console.log('❌ 图片加载失败:', url, '错误:', e)
    
    // 尝试其他可能的路径
    const alternatives = [
      url.replace('/static/', '/'),
      url.replace('http://localhost:8085/static/', 'http://localhost:8085/'),
      url.replace('http://localhost:8085/', 'http://localhost:8085/static/')
    ]
    
    console.log('尝试替代路径:', alternatives)
    
    // 测试所有替代路径
    let tested = 0
    alternatives.forEach((alternativeUrl, index) => {
      if (alternativeUrl !== url) {
        console.log(`测试替代路径 ${index + 1}:`, alternativeUrl)
        testAlternativeUrl(alternativeUrl, () => {
          tested++
          if (tested === alternatives.length - 1) {
            ElMessage.warning('头像上传成功，但预览可能需要刷新页面')
          }
        })
      }
    })
  }
  
  img.src = url
}

// 测试替代URL
const testAlternativeUrl = (url, onComplete) => {
  const testImg = new Image()
  testImg.onload = () => {
    console.log('✅ 替代路径有效:', url)
    userForm.avatar = url  // 这里可以直接使用 userForm，因为它在作用域内
  }
  testImg.onerror = () => {
    console.log('❌ 替代路径无效:', url)
  }
  testImg.src = url
  setTimeout(onComplete, 1000)
}
// 刷新操作日志
const handleRefreshLogs = () => {
  fetchUserLogs()
}

// 刷新通知消息
const handleRefreshNotifications = () => {
  fetchUserNotifications()
}

// 标记通知为已读
const handleMarkRead = async (row) => {
  try {
    const res = await markNotificationRead(row.id)
    console.log('标记已读响应:', res)
    if (res.code === 200) {
      ElMessage.success('标记成功')
      fetchUserNotifications()
      fetchUserStatistics()
    } else {
      ElMessage.error('标记失败: ' + res.message)
    }
  } catch (error) {
    console.error('标记已读失败:', error)
  }
}

// 删除通知
const handleDeleteNotification = async (row) => {
  try {
    await ElMessageBox.confirm('确定要删除这条通知吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    try {
      const res = await deleteNotification(row.id)

      if (res.code === 200) {
        ElMessage.success('删除成功')
        fetchUserNotifications()
        fetchUserStatistics()
      } else {
        ElMessage.error('删除失败: ' + res.message)
      }
    } catch (error) {
      console.error('删除通知失败:', error)
    }
  } catch (error) {
    // 用户取消删除
  }
}

// 操作日志分页
const handleLogsSizeChange = (size) => {
  logsParams.size = size
  logsParams.page = 1
  fetchUserLogs()
}

const handleLogsCurrentChange = (page) => {
  logsParams.page = page
  fetchUserLogs()
}

// 通知消息分页
const handleNotificationsSizeChange = (size) => {
  notificationsParams.size = size
  notificationsParams.page = 1
  fetchUserNotifications()
}

const handleNotificationsCurrentChange = (page) => {
  notificationsParams.page = page
  fetchUserNotifications()
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 初始化
onMounted(() => {
  fetchUserInfo()
  fetchUserStatistics()
  fetchUserLogs()
  fetchUserNotifications()
})
</script>

<style scoped>
.profile {
  padding: 20px;
}

.header {
  margin-bottom: 20px;
}

.header h2 {
  font-size: 24px;
  color: #333;
  margin: 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.content-container {
  margin-top: 20px;
}

.user-card {
  height: fit-content;
}

.user-info {
  text-align: center;
  margin-bottom: 20px;
}

.avatar-container {
  position: relative;
  margin-bottom: 15px;
  display: inline-block;
}

.avatar-btn {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  opacity: 0;
  transition: opacity 0.3s;
}

.avatar-container:hover .avatar-btn {
  opacity: 1;
}

.user-info h3 {
  margin: 10px 0 5px;
  font-size: 18px;
  color: #333;
}

.user-role {
  margin: 5px 0;
  color: #409eff;
  font-weight: 500;
}

.user-id {
  margin: 5px 0;
  color: #999;
  font-size: 14px;
}

.user-stats {
  border-top: 1px solid #eee;
  padding-top: 15px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  font-size: 12px;
  color: #999;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.security-section {
  padding: 10px 0;
}

.security-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 0;
  border-bottom: 1px solid #eee;
}

.security-item:last-child {
  border-bottom: none;
}

.security-info h4 {
  margin: 0 0 5px;
  font-size: 16px;
  color: #333;
}

.security-info p {
  margin: 0;
  font-size: 14px;
  color: #999;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

@media (max-width: 768px) {
  .profile {
    padding: 10px;
  }

  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .security-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
</style>